package cn.aicnn.chatssespringboot.service.test;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ParseResult;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.Node;
import java.io.File;
import java.io.FileInputStream;

public class JavaSyntaxTreeParser {
    public static void main(String[] args) throws Exception {
        // 1. 指定要分析的Java文件路径
        File javaFile = new File("D:\\grade3\\software_measure\\software-metrics\\src\\main\\java\\cn\\aicnn\\chatssespringboot\\service\\Impl\\AccountServiceImpl.java");

        // 2. 创建JavaParser实例并解析文件
        JavaParser javaParser = new JavaParser();
        FileInputStream in = new FileInputStream(javaFile);
        ParseResult<CompilationUnit> parseResult = javaParser.parse(in);

        // 3. 检查解析是否成功
        if (parseResult.isSuccessful() && parseResult.getResult().isPresent()) {
            CompilationUnit cu = parseResult.getResult().get();

            // 4. 打印语法树
            printSyntaxTree(cu, 0);
        } else {
            System.err.println("解析失败: " + parseResult.getProblems());
        }
    }

    // 递归打印语法树
    private static void printSyntaxTree(Node node, int level) {
        // 缩进表示层级
        for (int i = 0; i < level; i++) {
            System.out.print("  ");
        }

        // 打印节点类型和详细信息
        System.out.println(node.getClass().getSimpleName() +
                " - " + node.toString().split("\n")[0].trim());

        // 递归处理子节点
        for (Node child : node.getChildNodes()) {
            printSyntaxTree(child, level + 1);
        }
    }
}